import {Component, ElementRef, OnInit} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {NzMessageService} from "ng-zorro-antd";
import {FetchService} from "../../../core/net/fetch.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {addDays, format} from "date-fns";
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
import {Rect, Topology} from "topology-core";
import {Options} from "topology-core/options";
import * as _ from "lodash";

@Component({
  selector: 'app-dispatch-st',
  templateUrl: './dispatch-st.component.html',
  styleUrls: ['../dispatch-common.scss', './dispatch-st.component.scss']
})
export class DispatchStComponent implements OnInit {
  dataList: any[] = [];

  zxData;
  rect: Rect;
  canvas: Topology;
  canvasOptions: Options = {};
  hoverItem = {
    top: '0px',
    left: '0px',
    alertLevel: '-',
    waterLevel: '-',
    limitTraffic: '-',
    flow: '-'
  };
  infoShow = false;
  rightTableData;
  rightTableLoading;
  basicOpts: any = {
    title: {
      text: "",
      x: "center",
      textStyle: {
        color: "#777",
        fontSize: 16
      }
    },
    color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b'],
    grid: {
      top: '10%',
      left: '8%',
      right: '8%',
      bottom: '8%',
      containLabel: true
    },
    tooltip: {
      trigger: "axis"
    },
/*    dataZoom: [{
      type: 'slider',// 图表下方的伸缩条
      show: true, // 是否显示
      realtime: true, // 拖动时，是否实时更新系列的视图
      start: 0, // 伸缩条开始位置（1-100），可以随时更改
      end: 60, // 伸缩条结束位置（1-100），可以随时更改
    }],*/
    xAxis: {
      data: []
    },
    yAxis: {
      type: "value"
    }
  };
  customOpts: any = {};
  chartTitle = '';
  searchForm: FormGroup;
  rangePickerValue = [addDays(new Date(), -15), new Date()];
  selecteRow: any = {};
  drbsTotal = 0; // 当日补水
  ljbsTotal = 0; // 累计补水

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private el: ElementRef,
    private router: Router,
    private sanitizer: DomSanitizer
  ) {
    this.searchForm = this.fb.group({
      key: ['']
    });
  }

  ngOnInit(): void {
    window.addEventListener('resize', this.debounce(() => {
      this.onResize();
    }, 500));
    this.getMapData();
    this.getTableData();
  }

  // 防抖函数
  debounce(func, wait?, immediate?): any {
    let timeout;
    return () => {
      const context = this;
      const args = arguments;
      const later = () => {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  // 窗口变化
  onResize() {
    console.log('windonw is resize');
    const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
    const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
    this.rect = this.canvas.getRect();
    if (this.rect.width / this.rect.height > w / h) {
      this.canvas.scale(w / this.rect.width * 0.9);
    } else {
      this.canvas.scale(h / this.rect.height * 0.95);
    }
    this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
  }

  // 概化图元素事件
  onMouseEvent(event: string, node: any): void {
    if (event === 'moveInNode') {
      if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
        console.log(event, node);
        this.infoShow = true;
        const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
        const featureH = _.max(yArr) - _.min(yArr);
        console.log(featureH);
        this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
        this.hoverItem.left = (node.rect.center.x - 76) + 'px';

        const nodeId = node.data.cid;
        this.zxData.map(item => {
          if (item.objId == nodeId) {
            this.hoverItem.alertLevel = item.alertLevel || '-';
            this.hoverItem.flow = item.flow || '-';
            this.hoverItem.limitTraffic = item.limitTraffic || '-';
            this.hoverItem.waterLevel = item.waterLevel || '-';
          }
        });
      }
    }
    if (event === 'moveOutNode') {
      this.infoShow = false;
      this.hoverItem.alertLevel = '-';
      this.hoverItem.flow = '-';
      this.hoverItem.limitTraffic = '-';
      this.hoverItem.waterLevel = '-';
    }
    if (event === 'node') {
      // alert(node.data.name + '被点击了');
    }
  }

  getMapData(): void {
    this.fetchService.post<any>('report/ecology/queryTodayMapData', {}).subscribe(r => {
      this.zxData = r;
      this.fetchService.get<any>('assets/data/zxnew/st.json').subscribe(res => {
        const pens = res.pens;
        // 数据处理
        this.zxData.map(feature => {
          for (const pen of pens) {
            // 修改t 当天
            if (pen.data.id == `${feature.id}t`) {
              pen.text = feature.val ? feature.val + '万m³' : '-万m³';
            }
            // 修改s 累计
            if (pen.data.id == `${feature.id}s`) {
              pen.text = feature.sumVal ? feature.sumVal + '万m³' : '-万m³';
            }
          }
        });

        if (this.canvas) {
          // 重置画布数据
          this.canvas.open({
            id: '',
            version: '',
            name: 'new空白文件',
            desc: '',
            image: '',
            userId: '',
            class: '',
            component: false,
            shared: false
          });
        } else {
          // 创建画布
          this.canvasOptions.on = this.onMouseEvent.bind(this);
          this.canvas = new Topology('zx-canvas', this.canvasOptions);
        }
        this.canvas.open(res);

        // 设置画布
        this.onResize();
      });
    });
  }

  goPage(pageName): void {
    this.router.navigate([`/realtime-control/dispatch-${pageName}`]);
  }

  getTableData(): any {
    // 湖泊补水
    this.rightTableLoading = true;
    this.fetchService.post<any>('muw/wrsMuwLwData/list', {frId: 22}).subscribe(res => {
      this.rightTableLoading = false;
      this.rightTableData = res.wrsMuwLwDatas;
      res.wrsMuwLwDatas.map(item => {
        this.drbsTotal += item.val;
        this.ljbsTotal += item.valTotal;
      });
      this.selectedRow(res.wrsMuwLwDatas[0]);
    });
  }

  rangePickerValueChange(e): void {
    this.getChartData();
  }

  selectedRow(data): void {
    this.selecteRow = data;
    this.getChartData();
  }

  getChartData(): void {
    const params = {
      frId: 22,
      rrId: this.selecteRow.rrId,
      startDate: this.rangePickerValue[0].getTime(),
      endDate: this.rangePickerValue[1].getTime()
    };
    this.fetchService.post<any>('muw/wrsMuwLwData/historyDataList', params).subscribe(res => {
      const xAxisArr = res.map(item => {
        return format(item.time, 'DD日');
      });
      const seriesData = res.map(results => {
        return results.wrsMuwLwDatas[0].valTotal;
      });
      this.chartTitle = `${this.selecteRow.rrName}日补水总量过程曲线`;
      this.customOpts = {
        xAxis: {
          data: xAxisArr
        },
        yAxis: {
          name: '补水量(万m³)'
        },
        series: [
          {
            name: '补水量',
            type: 'line',
            data: seriesData
          }
        ]
      };
    });
  }

}
